package com.example.myapplication8.ui.sidebar

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Switch
import android.widget.Toast
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.myapplication8.R
import android.content.Context
import android.content.ClipData
import android.content.ClipboardManager
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.fragment.findNavController
import com.google.android.material.navigation.NavigationView
import com.example.myapplication8.MainActivity
import androidx.core.content.ContextCompat

/**
 * 侧边栏设置Fragment
 * 处理各种权限设置和功能开关
 */
class NavSettingsFragment : Fragment() {

    // 视图绑定
    private var _binding: View? = null
    private val binding get() = _binding!!

    // ViewModel
    private lateinit var viewModel: SidebarViewModel
    
    // Manager
    private lateinit var manager: SidebarManager

    private lateinit var navController: NavController
    private var currentNavItem = R.id.nav_transform

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // 加载布局
        _binding = inflater.inflate(R.layout.nav_settings_layout, container, false)
        return binding
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        try {
            // 初始化ViewModel
            viewModel = ViewModelProvider(this).get(SidebarViewModel::class.java)
            
            // 初始化Manager
            manager = SidebarManager.getInstance(requireContext())
            
            // 设置导航监听
            setupNavigation()
            
            // 恢复保存的状态
            savedInstanceState?.let { state ->
                // 恢复之前保存的状态
                currentNavItem = state.getInt(KEY_CURRENT_NAV_ITEM, R.id.nav_transform)
            }

            // 初始化各个设置项
            setupAccessibilityService()
            setupOverlayPermission()
            setupForegroundService()
            setupQQGroup()
            setupRunLog()
            setupVersion()
            setupAbout()
            setupHelp()

            // 观察数据变化
            observeViewModel()
        } catch (e: Exception) {
            Log.e(TAG, "Error in onViewCreated: ${e.message}")
            Toast.makeText(context, "导航初始化失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun setupNavigation() {
        try {
            // 获取导航控制器
            navController = findNavController()
            
            // 获取MainActivity中的NavigationView
            val mainActivity = requireActivity()
            val navigationView = mainActivity.findViewById<NavigationView>(R.id.nav_view)
            
            // 设置导航项点击监听
            navigationView?.setNavigationItemSelectedListener { menuItem ->
                try {
                    when (menuItem.itemId) {
                        R.id.nav_transform,
                        R.id.nav_reflow,
                        R.id.nav_slideshow,
                        R.id.nav_settings -> {
                            // 保存当前选中的导航项
                            currentNavItem = menuItem.itemId
                            // 执行导航
                            navController.navigate(menuItem.itemId)
                            // 关闭抽屉
                            (activity as? MainActivity)?.closeDrawer()
                            true
                        }
                        else -> false
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "Navigation error: ${e.message}")
                    Toast.makeText(context, "导航失败", Toast.LENGTH_SHORT).show()
                    false
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error setting up navigation: ${e.message}")
            Toast.makeText(context, "导航设置失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        // 保存当前导航状态
        outState.putInt(KEY_CURRENT_NAV_ITEM, currentNavItem)
    }

    /**
     * 观察ViewModel数据变化
     */
    private fun observeViewModel() {
        viewModel.accessibilityEnabled.observe(viewLifecycleOwner) { enabled ->
            updateAccessibilityUI(enabled)
        }

        viewModel.overlayPermissionGranted.observe(viewLifecycleOwner) { granted ->
            updateOverlayUI(granted)
        }

        viewModel.foregroundServiceRunning.observe(viewLifecycleOwner) { running ->
            updateForegroundServiceUI(running)
        }

        viewModel.versionInfo.observe(viewLifecycleOwner) { version ->
            binding.findViewById<TextView>(R.id.version_text).text = version
        }

        viewModel.logContent.observe(viewLifecycleOwner) { log ->
            if (log.isNotEmpty()) {
                showLogDialog(log)
            }
        }
    }

    /**
     * 设置无障碍服务开关
     */
    private fun setupAccessibilityService() {
        try {
            val switch = binding.findViewById<Switch>(R.id.accessibility_switch)
            val enabled = manager.isAccessibilityServiceEnabled()
            viewModel.updateAccessibilityStatus(enabled)

            switch.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked && !enabled) {
                    try {
                        startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
                    } catch (e: Exception) {
                        Log.e("NavSettings", "Error opening accessibility settings: ${e.message}")
                        Toast.makeText(context, "无法打开无障碍设置", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("NavSettings", "Error setting up accessibility service: ${e.message}")
        }
    }

    /**
     * 更新无障碍服务UI
     */
    private fun updateAccessibilityUI(enabled: Boolean) {
        try {
            binding.findViewById<Switch>(R.id.accessibility_switch).isChecked = enabled
            binding.findViewById<TextView>(R.id.accessibility_status)?.apply {
                text = if (enabled) {
                    "已开启 (服务正常运行)"
                } else {
                    "未开启 (点击开关前往设置)"
                }
                setTextColor(ContextCompat.getColor(requireContext(),
                    if (enabled) android.R.color.holo_green_dark 
                    else android.R.color.holo_red_dark
                ))
            }
            
            // 如果服务未启用，显示提示信息
            if (!enabled) {
                Toast.makeText(
                    context,
                    "请在系统设置中开启无障碍服务，否则部分功能可能无法使用",
                    Toast.LENGTH_LONG
                ).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error updating accessibility UI: ${e.message}")
        }
    }

    /**
     * 设置悬浮窗权限开关
     */
    private fun setupOverlayPermission() {
        try {
            val switch = binding.findViewById<Switch>(R.id.overlay_switch)
            val hasPermission = manager.hasOverlayPermission()
            viewModel.updateOverlayPermission(hasPermission)

            switch.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked && !hasPermission) {
                    try {
                        val intent = Intent(
                            Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:${requireContext().packageName}")
                        )
                        startActivity(intent)
                    } catch (e: Exception) {
                        Log.e("NavSettings", "Error opening overlay settings: ${e.message}")
                        Toast.makeText(context, "无法打开悬浮窗设置", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("NavSettings", "Error setting up overlay permission: ${e.message}")
        }
    }

    /**
     * 更新悬浮窗权限UI
     */
    private fun updateOverlayUI(granted: Boolean) {
        try {
            binding.findViewById<Switch>(R.id.overlay_switch).isChecked = granted
            binding.findViewById<TextView>(R.id.overlay_status)?.apply {
                text = if (granted) "已授权" else "未授权"
                setTextColor(ContextCompat.getColor(requireContext(),
                    if (granted) android.R.color.holo_green_dark 
                    else android.R.color.holo_red_dark
                ))
            }
        } catch (e: Exception) {
            Log.e("NavSettings", "Error updating overlay UI: ${e.message}")
        }
    }

    /**
     * 设置前台服务开关
     */
    private fun setupForegroundService() {
        try {
            val switch = binding.findViewById<Switch>(R.id.foreground_switch)
            switch.setOnCheckedChangeListener { _, isChecked ->
                try {
                    if (isChecked) {
                        manager.startForegroundService()
                    } else {
                        manager.stopForegroundService()
                    }
                    viewModel.updateForegroundService(isChecked)
                } catch (e: Exception) {
                    Log.e("NavSettings", "Error toggling foreground service: ${e.message}")
                    Toast.makeText(context, "操作失败，请重试", Toast.LENGTH_SHORT).show()
                    switch.isChecked = !isChecked
                }
            }
        } catch (e: Exception) {
            Log.e("NavSettings", "Error setting up foreground service: ${e.message}")
        }
    }

    /**
     * 更新前台服务UI
     */
    private fun updateForegroundServiceUI(running: Boolean) {
        try {
            binding.findViewById<Switch>(R.id.foreground_switch).isChecked = running
            binding.findViewById<TextView>(R.id.foreground_status)?.apply {
                text = if (running) "运行中" else "已停止"
                setTextColor(ContextCompat.getColor(requireContext(),
                    if (running) android.R.color.holo_green_dark 
                    else android.R.color.holo_red_dark
                ))
            }
        } catch (e: Exception) {
            Log.e("NavSettings", "Error updating foreground service UI: ${e.message}")
        }
    }

    /**
     * 设置QQ群点击事件
     */
    private fun setupQQGroup() {
        binding.findViewById<View>(R.id.qq_group_layout).setOnClickListener {
            try {
                val qqUrl = manager.getQQGroupUrl()
                try {
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl)))
                } catch (e: Exception) {
                    // 如果没有安装QQ，提供复制群号的选项
                    val groupNumber = manager.getQQGroupNumber()
                    Toast.makeText(context, "未安装QQ，已复制群号：$groupNumber", Toast.LENGTH_LONG).show()
                    val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    val clip = ClipData.newPlainText("QQ群号", groupNumber)
                    clipboard.setPrimaryClip(clip)
                }
            } catch (e: Exception) {
                Log.e("NavSettings", "Error handling QQ group: ${e.message}")
            }
        }
    }

    /**
     * 设置运行日志点击事件
     */
    private fun setupRunLog() {
        binding.findViewById<View>(R.id.run_log_layout).setOnClickListener {
            try {
                val logContent = manager.getRunningLog()
                viewModel.updateLogContent(logContent)
            } catch (e: Exception) {
                Log.e("NavSettings", "Error reading log: ${e.message}")
                Toast.makeText(context, "无法读取日志", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 显示日志对话框
     */
    private fun showLogDialog(logContent: String) {
        try {
            AlertDialog.Builder(requireContext())
                .setTitle("运行日志")
                .setMessage(logContent)
                .setPositiveButton("清除") { _, _ ->
                    try {
                        manager.clearRunningLog()
                        Toast.makeText(context, "日志已清除", Toast.LENGTH_SHORT).show()
                    } catch (e: Exception) {
                        Log.e("NavSettings", "Error clearing log: ${e.message}")
                        Toast.makeText(context, "清除失败", Toast.LENGTH_SHORT).show()
                    }
                }
                .setNegativeButton("关闭", null)
                .show()
        } catch (e: Exception) {
            Log.e("NavSettings", "Error showing log dialog: ${e.message}")
        }
    }

    /**
     * 设置版本信息
     */
    private fun setupVersion() {
        try {
            val versionInfo = manager.getVersionInfo()
            viewModel.updateVersionInfo(versionInfo)
        } catch (e: Exception) {
            Log.e("NavSettings", "Error setting up version: ${e.message}")
        }
    }

    /**
     * 设置关于信息
     */
    private fun setupAbout() {
        binding.findViewById<View>(R.id.about_layout)?.setOnClickListener {
            try {
                AlertDialog.Builder(requireContext())
                    .setTitle(getString(R.string.about_title))
                    .setMessage(getString(R.string.about_message))
                    .setPositiveButton(getString(R.string.about_confirm), null)
                    .show()
            } catch (e: Exception) {
                Log.e("NavSettings", "Error showing about dialog: ${e.message}")
            }
        }
    }

    /**
     * 设置帮助信息
     */
    private fun setupHelp() {
        binding.findViewById<View>(R.id.help_layout)?.setOnClickListener {
            try {
                AlertDialog.Builder(requireContext())
                    .setTitle(getString(R.string.help_title))
                    .setMessage(getString(R.string.help_message))
                    .setPositiveButton(getString(R.string.help_confirm), null)
                    .show()
            } catch (e: Exception) {
                Log.e("NavSettings", "Error showing help dialog: ${e.message}")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 更新各项状态
        try {
            viewModel.updateAccessibilityStatus(manager.isAccessibilityServiceEnabled())
            viewModel.updateOverlayPermission(manager.hasOverlayPermission())
        } catch (e: Exception) {
            Log.e("NavSettings", "Error updating status on resume: ${e.message}")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        private const val TAG = "NavSettingsFragment"
        private const val KEY_CURRENT_NAV_ITEM = "current_nav_item"
    }
} 